﻿
Imports System.Threading

Namespace locks
    Public Structure eventlock
        Implements ilock

        Private are As AutoResetEvent

        Public Sub enter() Implements ilock.enter
            If are Is Nothing Then
                Dim a As AutoResetEvent = Nothing
                a = New AutoResetEvent(True)
                If Not Interlocked.CompareExchange(are, a, Nothing) Is Nothing Then
                    a.Close()
                End If
            End If

            assert(are.WaitOne())
        End Sub

        Public Sub [exit]() Implements ilock.exit
            assert(are.Set())
        End Sub

        Public Function thread_owned() As Boolean Implements ilock.thread_owned
            Return False
        End Function

        Protected Overrides Sub Finalize()
            are.Close()
            GC.KeepAlive(are)
        End Sub
    End Structure
End Namespace
